package site.shenjie.jdbctemplate.controller;

import cn.hutool.core.bean.BeanUtil;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.shenjie.common.dao.entity.User;
import site.shenjie.common.model.ResponseModel;
import site.shenjie.jdbctemplate.model.InsertUserParam;

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author ShenJie
 * 2022/2/15 16:50
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 注册用户
     */
    @PostMapping("/insertUser")
    public ResponseModel insertUser(@Validated @RequestBody InsertUserParam param) {
        // 1. 检查手机号和邮箱（若有填写邮箱）是否已经被使用过
        List<User> users;

        StringBuilder sb = new StringBuilder();
        sb.append("""
                SELECT *
                FROM `user` u
                """);
        sb.append("WHERE u.`phone` = '").append(param.getPhone()).append("'");

        if (!StringUtils.isNullOrEmpty(param.getEmail())) {
            sb.append(" OR u.`email` = '").append(param.getEmail()).append("'");
        }

        users = jdbcTemplate.query(sb.toString(), BeanPropertyRowMapper.newInstance(User.class));

        // 若：使用过，则：发出警告
        if (users.size() > 0) {
            return ResponseModel.getWarning("用户已存在！", null);
        }

        // 否，则：尝试新增用户
        String insertSqlString = """
                INSERT INTO `user` (name,phone,email,password,create_time,login_time)
                VALUES(?,?,?,?,?,?)
                """;
        KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(con -> {
            PreparedStatement ps = con.prepareStatement(insertSqlString, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, param.getName());
            ps.setString(2, param.getPhone());
            ps.setString(3, StringUtils.isNullOrEmpty(param.getEmail()) ? null : param.getEmail());
            ps.setString(4, param.getPassword());
            ps.setTimestamp(5, Timestamp.valueOf(LocalDateTime.now()));
            ps.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now()));
            return ps;
        }, holder);

        // 最后将新增用户信息返回给前端
        User user = new User();
        BeanUtil.copyProperties(param, user);
        user.setAid(Objects.requireNonNull(holder.getKey()).intValue());
        return ResponseModel.getSuccess(null, user);
    }
}
